package com.aidex.web.controller.risk;

import com.aidex.common.core.text.Convert;
import com.aidex.common.utils.DateUtils;
import com.aidex.common.utils.JsonHelper;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.http.HttpUtils;
import com.aidex.config.InitMq;
import com.aidex.risk.domain.*;
import com.aidex.system.domain.*;
import com.aidex.system.event.LogEvent;
import com.aidex.system.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.logging.log4j.EventLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@RestController
@RequestMapping("/tradeRisk")
public class TradeRiskController {

    @Autowired
    private WaybillService waybillService;
    @Autowired
    private WaybillDetailService waybillDetailService;

    @Autowired
    private SyncEmergencyFlightService syncEmergencyFlightService;
    @Autowired
    private VInternationalAsdService vInternationalAsdService;
    @Autowired
    private VInternationalRecordService vInternationalRecordService;
    @Autowired
    private VInternationalReleaseService vInternationalReleaseService;
    @Autowired
    private VInternationalUnpackingService vInternationalUnpackingService;

    @Autowired
    private RunLogService runLogService;
    private static final Logger log = LoggerFactory.getLogger(InitMq.class);

    @Autowired
    private ApiLogService apiLogService;
    //运单数据
    @PostMapping("/syncTrade")
    public resultRiskResponse syncTrade(@Validated @RequestBody syncMethod<transData> info) {
        log.info("syncTrade接收到数据：{}", JSON.toJSONString(info));
        resultRiskResponse result = new resultRiskResponse();
        SimpleDateFormat nowDataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();

        try {
            if (info != null && info.getData() != null) {
                waybillService.Save(info);
            }
            result.setStatus(200);
            result.setMessage("success");
            result.setTimestamp(nowDataFormat.format(date));
            apiLogService.updateScuess("运单API接收");
            return result;
        } catch (Exception ex) {
            log.error("syncTrade运单接收错误：" + ex.getMessage());
            result.setStatus(-1);
            result.setMessage("error");
            result.setTimestamp(nowDataFormat.format(date));
            apiLogService.updateError("运单API接收");
            runLogService.saveError("运单API接收错误","发生错误，请查看错误日志");

            return result;
        }
    }

    //开箱结果数据
    @PostMapping("/syncRiskratingRiskmarking")
    public resultRiskResponse syncRiskratingRiskmarking(@Validated @RequestBody syncMethod<List<international_riskrating_riskmarking>> dtoList) {
        resultRiskResponse result = new resultRiskResponse();
        String json = JsonHelper.getInstance().writeValueAsString(dtoList);
        log.info("test debug syncRiskratingRiskmarking接收到数据：" + json);
        LogEvent event = new LogEvent();
        event.setApiType("International开箱数据接收");
        try {
            List<international_riskrating_riskmarking> infoList = dtoList.getData();
            if (infoList != null && infoList.stream().count()>0) {
                for(international_riskrating_riskmarking info:infoList) {
                    VInternationalAsd asd = new VInternationalAsd();
                    asd.setAwbno(info.getWayBillID());
                    asd.setMwbno(info.getWayBillNo());
                    asd.setHwbno(info.getSubWayBillNo());
                    asd.setAgentshipname(info.getAgentShipName());
                    asd.setCarriercode(info.getCarrierCode());
                    asd.setFlightno(info.getFlightNo());
                    List<international_riskrating_riskmarking.CheckDataDTO> checkDataList = info.getCheckData();
                    List<international_riskrating_riskmarking.OpenBoxDTO> openBoxList = info.getOpenBox();
                    vInternationalAsdService.save(asd);
                    for (international_riskrating_riskmarking.CheckDataDTO item : checkDataList) {
                        VInternationalRecord record = new VInternationalRecord();
                        record.setCheckpoint(item.getCheckPoint());
                        record.setSecuritypcs(Convert.toLong(item.getSecurityPcs()));
                        record.setStarttime(StringToDateTime(item.getStartTime()));
                        record.setEndtime(StringToDateTime(item.getEndTime()));
                        record.setIsPast(item.getIsPast());
                        record.setMwbno(info.getWayBillNo());
                        record.setHwbno(info.getSubWayBillNo());
                        VInternationalRelease release = new VInternationalRelease();
                        release.setMwbno(info.getWayBillNo());
                        release.setHwbno(info.getSubWayBillNo());
                        release.setReleasetime(StringToDateTime(item.getReleaseTime()));
                        release.setReleaseoptr(item.getReleaseOptr());
                        vInternationalRecordService.save(record);
                        vInternationalReleaseService.save(release);
                    }
                    for (international_riskrating_riskmarking.OpenBoxDTO item : openBoxList) {
                        VInternationalUnpacking unpacking = new VInternationalUnpacking();
                        unpacking.setMwbno(info.getWayBillNo());
                        unpacking.setHwbno(info.getSubWayBillNo());
                        unpacking.setCargoname(item.getIllegalCargoName());
                        unpacking.setCount(Convert.toLong(item.getCount()));
                        unpacking.setResult(item.getResult());
                        vInternationalUnpackingService.save(unpacking);
                    }
                }
            }
            result.setStatus(200);
            result.setMessage("success");
            event.setSuccess(true);
            result.setTimestamp( DateUtils.getTime());
            apiLogService.updateScuess("International开箱数据接收");
        } catch (Exception e) {
            event.setSuccess(false);
            log.error("syncRiskratingRiskmarking接收到数据：" + json+e.getMessage());
            result.setStatus(-1);
            result.setMessage("error");
            result.setTimestamp(DateUtils.getTime());
            log.error(e.getMessage());
            apiLogService.updateError("International开箱数据接收");
            runLogService.saveError("开箱API接收错误","发生错误，请查看错误日志");
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/test")
    public void test(Integer flag) {
       /* if(flag==1){
            apiLogService.updateScuess("test");
        }else {
            apiLogService.updateError("test");
        }*/
        waybillService.syncWlptSpecialGoods();
    }

    @GetMapping("/sendLevelReslut")
    public String sendLevelReslut(String waybillNO,String datasource) throws JsonProcessingException {
        Long start = System.currentTimeMillis();
        String reslult = waybillService.sendTradeGoodsRiskByWaybillApi(waybillNO,datasource);
        log.info("sendLevelReslut: {}, 耗时: {}ms", reslult,System.currentTimeMillis() - start);
        return reslult;
    }

    @GetMapping("/queryVCsis")
    public void queryVCsis(Integer day) throws JsonProcessingException {
        Long start = System.currentTimeMillis();
        waybillService.queryVCsis(day);
        log.info("开箱数据请求结果: {}, 耗时: {}ms", "OK",System.currentTimeMillis() - start);
    }

   /* Date StringToDateTime(String strDate) throws ParseException {

        strDate = strDate.replaceAll("T", " ");
        //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateTime;
        try {
            dateTime = DateUtils.parseDate(strDate, "yyyy-MM-dd HH:mm:ss");
            return dateTime;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new Date(1970,0,0);
    }*/

    Date StringToDateTime(String strDate) {
        try {
            strDate = strDate.replaceAll("T", " ");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
            Date dateTime;
            dateTime = formatter.parse(strDate);
            return dateTime;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new Date(1970,0,0);
    }

    public static void main(String[] args) throws ParseException {
        System.out.println(DateUtils.parseDate("2021-10-22 09:12:11", "yyyy-MM-dd HH:mm:ss"));
    }
}
